//
//  ViewControllerLogin.swift
//  AirlineReservation
//
//  Created by Kevin on 2019/12/26.
//  Copyright © 2019 Kevin. All rights reserved.
//

import UIKit

class VCLogin: VCBase {
    
    // 登录布局
    private lazy var loginView: LoginView = {
        let ui = LoginView()
        ui.delegate = self
        ui.moreLabel.isHidden = true
        ui.backgroundColor = UIColor.white
        ui.frame = CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: SCREEN_HEIGHT)
        return ui
    }()
    
    // 快捷登录布局
    private lazy var loginBiometricView:LoginBiometricView = {
        let ui = LoginBiometricView()
        ui.delegate = self
        ui.backgroundColor = UIColor.white
        ui.frame = CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: SCREEN_HEIGHT)
        return ui
    }()
    
    // 用户主动退出
    public var isExit:Bool = false
    
    // 人脸是否开通
    private var isFaceOn:Bool = false
    // 指纹是否开通
    private var isFingerOn:Bool = false
    // 手势是否开通
    private var isGestureOn:Bool = false
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        init_views()
    }
}

// MARK: 快捷登录布局代理
extension VCLogin: LoginBiometricViewDelegate {
    
    // 快捷登录
    func clickBiometric() {
        process { (isOK, type) in
            if isOK {
                self.updateRootVc()
            }
        }
    }
    
    func clickSwitchBtn() {
        let alert = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
        // 手势登录
        if isGestureOn {
            alert.addAction(UIAlertAction(title: "手势登录", style: .default, handler: { (action) in
                self.present(self.loginUseGesture(), animated: true, completion: nil)
            }))
        }
        // 账号密码登录
        alert.addAction(UIAlertAction(title: "密码登录", style: .default, handler: { (action) in
            self.loginBiometricView.removeFromSuperview()
            self.view.addSubview(self.loginView)
        }))
        // 取消按钮
        alert.addAction(UIAlertAction(title: "取消", style: .cancel, handler: nil))
        present(alert, animated: true, completion: nil)
    }
}

// MARK: 登录布局代理
extension VCLogin: LoginViewDelegate {
    
    // 插入模拟数据
    func selectFakeData() {
        let vc = VCWeb()
        vc.pageapi = "fakedata/0"
        self.pushNextVcHideShowBottomBar(vc: vc)
    }
    
    // 选择服务器
    func selectServer() {
        self.pushVcHideBottomBar(title: "修改服务器地址", vc: VCServer())
    }
    
    // 切换登录方式
    func clickLoginSwitchBtn() {
        let alert = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
        // 手势登录
        if isGestureOn {
            alert.addAction(UIAlertAction(title: "手势登录", style: .default, handler: { (action) in
                self.present(self.loginUseGesture(), animated: true, completion: nil)
            }))
        }
        // 指纹登录
        if isFingerOn {
            alert.addAction(UIAlertAction(title: "指纹登录", style: .default, handler: { (action) in
                self.loginView.removeFromSuperview()
                self.view.addSubview(self.loginBiometricView)
                self.clickBiometric()
            }))
        }
        // 人脸登录
        if isFaceOn {
            alert.addAction(UIAlertAction(title: "人脸登录", style: .default, handler: { (action) in
                self.loginView.removeFromSuperview()
                self.view.addSubview(self.loginBiometricView)
                self.clickBiometric()
            }))
        }
        // 取消按钮
        alert.addAction(UIAlertAction(title: "取消", style: .cancel, handler: nil))
        present(alert, animated: true, completion: nil)
    }
    
    // 忘记密码
    func clickFotPwd() {
        let vc = VCModifyPwd()
        vc.title = "修改密码"
        pushNextVcHideBottomBar(vc: vc)
    }
    
    // 注册用户
    func clickRegUser() {
        let vc = VCCreateAccount()
        vc.title = "注册账号"
        pushNextVcHideBottomBar(vc: vc)
    }
    
    // 登录按钮
    func clicklogin(mobile: String?, password: String?) {
        if mobile?.count == 0 {
            self.show(text: "请输入手机号")
            return
        }
        if password?.count == 0 {
            self.show(text: "请输入密码")
            return
        }
        // 隐藏键盘
        view.endEditing(true)
        // 拼数据
        let dict = NSMutableDictionary()
        dict.setValue(mobile, forKey: SP_MOBILE)
        dict.setValue(password, forKey: SP_PASSWORD)
        // 请求
        doPost(api: "search/account", dict: dict) { (dict) in
            // 解析数据
            guard let result = dict.value(forKey: SP_BODYREQUEST) as? NSDictionary else {
                self.show(text: "服务端响应报文不正确")
                return
            }
            // 跳转到主界面
            guard let userid = result.value(forKey: "userid") as? String else {
                self.show(text: "服务端响应报文不正确.")
                return
            }
            self.updateRootVc(userid: userid)
        }
    }
    
    func updateRootVc(userid:String? = nil) -> Void {
        // 拼接数据
        var uid = userid
        if userid == nil {
            uid = UserDefaults.standard.string(forKey: SP_USERID)
        }
        let request = NSMutableDictionary()
        request.setValue(uid, forKey: SP_USERID)
        // 请求
        self.doPost(api: "search/user", dict: request) { (dict) in
            // 解析数据
            guard let result = dict.value(forKey: SP_BODYREQUEST) as? NSDictionary else {
                return
            }
            let userInfo = UserInfo(dict: result as! [String : Any])
            // 存数据
            self.saveUserInfo(userInfo: userInfo)
            // 更新视图
            NotificationCenter.default.post(name: CUSTOM_SWITCH_NOTIFICATIONCENTER, object: "main")
        }
    }
}

// MARK: 初始化
extension VCLogin {
    
    // 登录数据
    private func loginUserDict(user:String) -> NSDictionary {
        let dict = NSMutableDictionary()
        dict.setValue(UIDevice.current.identifierForVendor?.uuidString, forKey: "deviceid")
        dict.setValue(user, forKey: SP_USERNAME)
        return dict
    }
    
    // 手势登录
    func loginUseGesture() -> UIViewController {
        let lock9View = Lock9ViewController()
        lock9View.isTwo = false
        lock9View.callback = {password,status in
            if status == GestureStatus.SUCCESS {
                let pwd = UserDefaults.standard.string(forKey: SP_GESTURE_LOGIN_PWD)
                if !pwd!.elementsEqual(password) {
                    self.show(text: "您输入的手势不正确！")
                    return
                }
                self.updateRootVc()
            }
        }
        return lock9View
    }
    
    // 更新登录布局
    func updateLoginView(isBiometric:Bool) -> Void {
        if isBiometric {
            loginView.removeFromSuperview()
            view.addSubview(loginBiometricView)
        }else {
            loginBiometricView.removeFromSuperview()
            view.addSubview(loginView)
        }
    }
    
    // 选择登录模式
    private func selectLoginMode(isFaceOn:Bool,isFingerOn:Bool,isGestureOn:Bool) -> Void {
        // 人脸登录
        if isFaceOn {
            self.updateLoginView(isBiometric: true)
            // 人脸图片
            loginBiometricView.resetBimoetricPic = 2
            // 直接弹人脸窗口
            process { (isOK, type) in
                if isOK {
                    self.updateRootVc()
                }
            }
            return
        }
        // 指纹登录
        if isFingerOn {
            self.updateLoginView(isBiometric: true)
            // 直接弹指纹窗口
            process { (isOK, type) in
                if isOK {
                    self.updateRootVc()
                }
            }
            return
        }
        // 手势登录
        if isGestureOn {
            // 直接弹手势窗口
            self.present(loginUseGesture(), animated: true, completion: nil)
            return
        }
    }
    
    private func init_views() -> Void {
        guard (UserDefaults.standard.value(forKey: SP_MOBILE) as? String) != nil else {
            view.addSubview(loginView)
            return
        }
        if isExit {
            view.addSubview(loginView)
            return
        }
        // 首先显示账号密码布局
        updateLoginView(isBiometric: false)
        // 本地 生物识别是否开通
        let biometric = UserDefaults.standard.integer(forKey: SP_BIOMETRIC_LOGIN_PWD)
        if biometric == 1 {
            isFingerOn = true
        }
        if biometric == 2 {
            isFaceOn = true
        }
        // 本地 手势识别是否开通
        let gesturePwd = UserDefaults.standard.string(forKey: SP_GESTURE_LOGIN_PWD)
        if gesturePwd != nil {
            isGestureOn = true
        }
        // 本地是否有开通
        if isFaceOn || isFingerOn || isGestureOn {
            loginView.resetMoreLableShow = false
            self.selectLoginMode(isFaceOn: isFaceOn, isFingerOn: isFingerOn, isGestureOn: isGestureOn)
            return
        }
    }
}
